﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace DeepEarth.Toolkit.Controls.Measure
{
    public class DistanceFormatConverter : IValueConverter
    {
        public DistanceFormatConverter()
        {
            IncludeUnits = true;
        }

        public string Convert(double value)
        {
            if (IncludeUnits)
            {
                return string.Format("{0:F2}", value);
            }
            else
            {
                string units = "m";

                if (value > 1000)
                {
                    value /= 1000.0;
                    units = "km";
                }
                return string.Format("{0:F} {1}", value, units);
            }
        }

        #region Properties
        public bool IncludeUnits { get; set; }
        #endregion

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value == null ? null : Convert((double)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }

    public class AreaFormatConverter : IValueConverter
    {
        public AreaFormatConverter()
        {
            IncludeUnits = true;
        }

        #region Properties
        public bool IncludeUnits { get; set; }
        #endregion

        string Convert(double value)
        {
            if (IncludeUnits)
            {
                return string.Format("{0:F3}", value);
            }
            else
            {
                string units = "m\u00b2";

                if (value > 100000)
                {
                    value /= 1000000.0;
                    units = "km\u00b2";
                }
                return string.Format("{0:F3} {1}", value, units);
            }
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            if (double.IsNaN((double)value))
                return "Area could not be calculated";

            return Convert((double)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
}